/*
 *	Molecule analyzer
 *
 *	Copyright (C) 2011 XiaoJSoft Studio. All Rights Reserved.
 *	Copyright (C) Ji WenCong <whs_jwc@163.com>
 *
 *	kasprintf (copied & modified from Linux Kernel):
 *	Copyright (C) Linus Torvalds <torvalds@klaava.Helsinki.Fi>
 *
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <stdio.h>
#include "../../localization/local.h"
#include "../../include/interpreter.h"
#include "../../include/console/utils/molecule.h"
#include "../../include/console/utils/atom.h"

/*
 *	void analysisMolecule(char *molecule);
 *
 *	to analysis a molecular
 *
 */
void analysisMolecule(char *molecule)
{
	element *anaret;
	int count;
	int idx;
	double moleweight;
	int useless = 0;

	if (molecule == NULL) {
		printf(localization_table[42]);
		return;
	}

	count = 0;

	anaret = analyzeElements(molecule, NULL, &count);
	if (anaret == NULL) {
		printf(localization_table[47]);
		return;
	}

	moleweight = 0;

	for (idx = 0; idx <= (count - 1); idx++) {
		if (atomExist((anaret + idx)->name) == -1) {
			printf(localization_table[48], (anaret + idx)->name);
			return;
		}
		moleweight += (anaret + idx)->count * getAtomHeavy((anaret + idx)->name, &useless);
	}

	if (moleweight <= 0) {
		printf(localization_table[49]);
		return;
	}

	printf(localization_table[50]);

	for (idx = 0; idx <= (count - 1); idx++) {
		printf("%s	%d	%f%%\n", chemical_enames[atomExist((anaret + idx)->name)], (int)((anaret + idx)->count), (double)((double)((anaret + idx)->count) * getAtomHeavy((anaret + idx)->name, &useless)) / moleweight * 100);
	}

	printf(localization_table[51]);

	printf(localization_table[52], molecule);
	printf(localization_table[53]);
	for (idx = 0; idx <= (count - 1); idx++) {
		if ((anaret + idx)->count == 0) {
			continue;
		}

		if ((anaret + idx)->count == 1) {
			printf("%s", chemical_enames[atomExist((anaret + idx)->name)]);
			continue;
		}

		if ((anaret + idx)->count < 0) {
			printf("%s(%d)", chemical_enames[atomExist((anaret + idx)->name)], (int)((anaret + idx)->count));
		} else {
			printf("%s%d", chemical_enames[atomExist((anaret + idx)->name)], (int)((anaret + idx)->count));
		}
	}
	printf("\n");

	printf(localization_table[54], moleweight);
}

